<template>
  <div>
    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="35%" v-dialog-drag append-to-body>
      <el-form ref="formRef" :model="formData" :rules="formRules" v-loading="formLoading" label-width="120">
        <el-form-item label="良品托盘/RFID编码" prop="goodCode">
          <el-input v-model="formData.goodCode" placeholder="请输入良品质托盘/RFID编码" style="width: 200px;"/>
        </el-form-item>
        <el-form-item label="良品物料箱码" prop="boxCode">
          <el-input v-model="formData.boxCode" placeholder="请输入良品物料箱编码" style="width: 200px;"/>
        </el-form-item>
        <el-form-item label="异常质检箱编码" prop="defectCode">
          <el-input v-model="formData.defectCode" placeholder="请输入异常质检箱编码" style="width: 200px;"/>
        </el-form-item>
        <el-form-item v-for="(item, index) in formData.inputRows"
                      :key="index"
                      :label="'产品码 ' + (index + 1)"
                      :prop="'inputRows.' + index + '.materialCode'"
                      :rules="formRules.items[0].materialCode">
          <div style="display: flex">
            <el-input v-model="item.materialCode" placeholder="请输入编码" style="width: 200px; margin-right: 10px;"></el-input>
            <el-checkbox v-model="item.isDefect" style="margin-left: 30px;" border>异常</el-checkbox>
            <el-button v-if="index > 0" type="text" icon="el-icon-delete" @click="removeItem(index)" style="color: red; margin-left: 30px;">删除</el-button>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="warning" plain @click="addInputRow">添加物料</el-button>
        <el-button type="primary" @click="submitForm" :disabled="formLoading">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as QcOrderApi from '@/api/hs/qcorder';
import {getMaterialModeByMaterialCode} from "@/api/hs/materialmode";

export default {
  name: "QcOrderForm",
  components: {},
  data() {
    return {
      // 弹出层标题
      dialogTitle: "",
      // 是否显示弹出层
      dialogVisible: false,
      // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
      formLoading: false,
      // 表单参数
      formData: {
        id: undefined,
        code: undefined,
        warehouseId: undefined,
        operator: undefined,
        defectCode: undefined,
        goodCode: undefined,
        boxCode: undefined,
        // 初始输入行数据
        inputRows: [{materialCode: '', isDefect : false}],
      },
      formRules: {
        items: [
          {
            materialCode: [
              {required: true, message: '编码不能为空', trigger: 'blur'}
            ]
          }
        ]
      },
      materialMode: undefined,
    };
  },
  methods: {
    /** 打开弹窗 */
    async open() {
      this.dialogVisible = true;
      this.reset();
      this.title = "新增质检单信息";
    },
    /** 提交按钮 */
    async submitForm() {
      // 校验主表
      await this.$refs["formRef"].validate();
      this.formLoading = true;
      try {
        const qcDetailList = [];
        this.formData.inputRows.forEach(row => {
          const { materialCode, isDefect} = row;
          const detail = {
            infoCode: isDefect ? this.formData.defectCode : this.formData.goodCode,
            boxCode: !isDefect ? this.formData.boxCode : '',
            materialCode: materialCode,
            qcResult: isDefect ? 1 : 0,
          };
          qcDetailList.push(detail);
        });
        const data = {
          ...this.formData,
          qcDetailList
        };
        for (let i = 0; i < qcDetailList.length; i++) {
          const item = qcDetailList[i];
          if (!item.infoCode) {
            this.$modal.msgError('请根据质检情况，分别填写良品和异常质检箱编码');
            return;
          }
        }
        if (qcDetailList.length === 0) {
          this.$modal.msgError('质检清单不能为空');
          return;
        }
        await QcOrderApi.createQcOrder(data);
        this.$modal.msgSuccess("新增成功");
        this.dialogVisible = false;
        this.$emit('success');
      } finally {
        this.formLoading = false;
      }
    },
    /** 表单重置 */
    reset() {
      this.formData = {
        id: undefined,
        code: undefined,
        warehouseId: undefined,
        operator: undefined,
        inputRows: [{materialCode: '', isDefect : false}],
      };
      this.resetForm("formRef");
    },
    /** 添加新的输入行 */
    async addInputRow() {
      if (!this.formData.boxCode) {
        this.$modal.msgError('请先填写物料箱编码');
        return;
      }
      if (!this.formData.inputRows[0].materialCode) {
        this.$modal.msgError('请先输入第一个物料编码');
        return;
      }
      if (this.formData.inputRows.length === 1) {
        this.materialMode = await this.getMaterialModeByMaterialCode(this.formData.inputRows[0].materialCode);
      }
      let goodCount = this.formData.inputRows.filter(item => !item.isDefect).length;
      if (goodCount >= this.materialMode.boxCapacityCount) {
        this.$modal.msgError('该物料箱内只能放' + this.materialMode.boxCapacityCount + '个良品物料');
        return;
      }
      this.formData.inputRows.push({materialCode: '', isDefect : false});
    },
    /** 删除指定索引的输入行 */
    removeItem(index) {
      if (index === 0) {
        return
      }
      this.formData.inputRows.splice(index, 1);
    },
    /** 根据物料编码获取机型信息 */
    async getMaterialModeByMaterialCode(materialCode) {
      const res = await getMaterialModeByMaterialCode(materialCode);
      if (!res.data) {
        this.$modal.msgError('未找到该物料对应的机型信息');
        return;
      }
      return res.data;
    }
  }
};
</script>
